const timeUtil = require("/utils/time")
const jobUtil = require("../../../../utils/jobUtil")
import {setOtherShareToken, getOtherShareToken, setSelfShareToken, getSelfShareToken, getUserToken } from '../../../../core/utils';
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:null,
    palette:{},//画图的模拟json
    // 岗位详情数据
    postInfo:{
      recruitWorkTime:{
        startDate:'',
        endDate:'',
        type: 1
      },
      workplacePictures: [],
      orgId: ''
    },
    painterView: false,
    dormitoryDistance:"",//宿舍距离
    educationRequire:"",//学历要求
    experienceRequire:"",//经验要求
    genderRequire:"",//性别要求
    ageRequire:"",//年龄要求

    updateTimeStr:"",//更新时间
    jobPayPrice:"",//工资
    jobPayUnit:"",//薪资单位
    jobType: 1,//工作类型（1：全职，2：兼职）
    longitude: 0,//经度
    latitude: 0,//纬度
    awayType: "",//距离文案
    fromSearch:false,//是否来至于搜索页面
    jobTime: '', // 早班 中班 晚班 其他
    jobTimeB: [], 
    
    workDate_1: '',	//工作时间过滤对象(工作日)
    workDate_2: '',	//工作时间过滤对象(双休日)
    work_arr:[],
    recommend_list: [],
    // 收藏传参  0:1
    operationType: -1,
    recruitId: '',//岗位推荐id
    tenantId: '',

    otherShareToken: '',		//他人分享token
    selfShareToken: '',		//自身分享token

    yearTime: [],
    dayTime: [],
    hoursTimeArr: [],
    hoursTime: [],
    hours: [
      "00:00","00:30","01:00","01:30","02:00","02:30","03:00","03:30","04:00","04:30","05:00","05:30", "06:00","06:30","07:00","07:30","08:00","08:30","09:00","09:30","10:00","10:30","11:00","11:30", "12:00","12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30", "18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00","22:30","23:00","23:30" 
    ],
    hasToken: false,//判断是否已登录
    type2_work_time: '',//兼职周期
    workTypeText: '',//工作类型(1：做一休一，2：做二休一，3：做二休二，4：做五休

    //微领队分享
    shareId: '',//来源微信朋友分享的shareId
    vleaderId: '',
    shareType : 10,// 分享类型 10:APP  30:V派

    intervier_apply_status: 0,		//申请面试-简历状态

    conflict_time: '',		//面试冲突时间
    conflict_post: '',		//面试冲突岗位

    // 取消面试相关字段
    cancelInterviewId: '',						//取消面试id
    cancelCheckId: '',						//取消原因索引
    cancelReason: '',				//提交取消原因内容
    anotherReason: '',			//文本框取消内容
    showAnother: false,			//是否显示取消文本框
    reasondata: [
      {
        status: false,
        text: '待遇不满意'
      },
      {
        status: false,
        text: '已经找到工作'
      },
      {
        status: false,
        text: '时间不合适'
      },
      {
        status: false,
        text: '太远了'
      },
      {
        status: false,
        text: '家庭原因'
      },
      {
        status: false,
        text: '其他原因'
      }
    ],
    failLoadPost: {
      isOwn: 0,
      name: ''
    },
    shareQrImg: "", //base64图片
    hadTap: false,//面试按钮是否可点击
    shareFlag: false,	//是否为分享进入
    invalid_vleader: false,		//微领队分享是否过期

    collectionOperationDis: false,//没有登录，不可点击收藏
    noTokenShareDis: false,
    showTimePopDis: false,
    bannerCurrent: 0,//图片索引
  },
  // 接口要的参数
  queryParams:{
    "id": null,
    "jobType": 1,
    "lat": 0,
    "lng": 0
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    let globalData = getApp().globalData;
    console.log(globalData)
    const passMap = JSON.parse(options.param)
    //岗位id保存
    this.id = passMap.id || '-1'
    this.jobType = passMap.jobType //工作类型(全职1,兼职2)
    this.shareId = passMap.shareId || '' //来源微信朋友分享的shareId
    this.shareFlag = passMap.shareFlag || false //是否为分享进入
    this.fromSearch = passMap.fromSearch;//是否来至于搜索页面
    this.awayType = globalData.awayType;//距离文案
    //1.搜索页面进来   2.noWant没有设置简历 没有设置期望地点 显示距离您多远 
    if(this.fromSearch || this.awayType == 'noWant'){
      this.awayText = '距离您'
    //3.want已设置简历 显示期望地点多远s
    }else{
      this.awayText =  '距离您期望工作地点'
    }
    // 其他人的分享token
		let otherShareToken = passMap.shareToken || getOtherShareToken()
		this.otherShareToken = otherShareToken?otherShareToken: ""
    this.shareType = passMap.creatorType ? option.creatorType:10 // 分享类型 10:APP  30:V派
    // 存他们分享token
    setOtherShareToken(this.otherShareToken)

    // 微派分享参数
    let data = passMap.scene?decodeURIComponent(passMap.scene):""
    console.log(data)
    if (data) {
      this.shareType = 30  // 分享类型 10:APP  30:V派
      this.shareFlag = true//是否为分享进入
      this.shareId = data.split(',')[1].split(':')[1]
			if(!this.shareId){
        wx.showToast({
          title: data
        })
			}
    }
    
  },
  /**
   * 页面出现时的方法
   */
  onShow(){
    let that = this
    let globalData = getApp().globalData;
    this.showTimePopDis = false
		this.noTokenShareDis = false
		this.collectionOperationDis = false
    this.hadTap = false
    
    //获取经纬度
    if(this.fromSearch){
      this.latitude = globalData.latitude;
      this.longitude = globalData.longitude;
    }else{
      this.latitude = globalData.latitude;
      this.longitude = globalData.longitude;
    }
    // 微派分享封装
    //微派APP分享
    if(this.shareType == 30){
      //获取分享令牌s
      othersVleaderShareToken()
      wx.openLocation({
        latitude: 31.188212,
        longitude: 121.436702,
      })
    } else {
      //获取岗位详情数据
      this.getDetail()
      //获取分享图片
			this.getShareImage()
			if( this.otherShareToken && this.shareFlag ){
        //校验分享岗位链接是否有效
				this.getLoadPost()
			}
    }
    //token
    const tempToken = getUserToken()
    this.hasToken = tempToken.length>0  ? true : false
    this.setData({
      hasToken: this.hasToken
    })
		if( !getSelfShareToken() ){
			wx.hideShareMenu({})
			if (this.hasToken) {
        //生成分享令牌
        app.$http.createShareToken().then(resData=>{
					setSelfShareToken(resData)
					that.selfShareToken = resData
					wx.showShareMenu({
						withShareTicket: true
					})
        })
			}
		}else{
			this.selfShareToken = getSelfShareToken()
		}
		// 判断微领队分享岗位是否失效

  },



  //请求岗位详情数据
  getDetail(){

    //请求岗位详情数据
    this.queryParams = {
      id: this.id,
      jobType: this.jobType,
      lat: this.latitude,
      lng: this.longitude
    }
    // console.log(this.queryParams)
    let that = this;
    app.$http.getJobDetail(this.queryParams).then(postRes=>{
      //保留原始返回数据
      console.log(JSON.stringify(postRes))
      //原始数据
      this.postInfo = postRes
      //岗位推荐
      this.recruitId = postRes.recruitId
      this.tenantId = postRes.tenantId

      //兼职周期
      let recruitWorkTime = postRes.recruitWorkTime
      this.type2_work_time = recruitWorkTime.startDate ? timeUtil.parseTime(recruitWorkTime.startDate,'{y}-{m}-{d}') + '~' + timeUtil.parseTime(recruitWorkTime.endDate,'{y}-{m}-{d}') : '长期'

      //工作班次过滤
      this.jobTimeB = []
      if( recruitWorkTime.morningShift ){
        this.jobTimeB.push(`早班 ${recruitWorkTime.morningShiftStart} - ${recruitWorkTime.morningShiftEnd}  `)
      }
      if( recruitWorkTime.middleShift ){
        this.jobTimeB.push(`中班 ${recruitWorkTime.middleShiftStart} - ${recruitWorkTime.middleShiftEnd}  `)
      }
      if( recruitWorkTime.eveningShift ){
        this.jobTimeB.push(`晚班 ${recruitWorkTime.eveningShiftStart} - ${recruitWorkTime.eveningShiftEnd}  `)
      }
      if( recruitWorkTime.otherShift ){
        this.jobTimeB.push(`其他班次 ${recruitWorkTime.otherShiftStart} - ${recruitWorkTime.otherShiftEnd}  `)
      }

      // 工作时间过滤
      if ( recruitWorkTime.shiftMon && recruitWorkTime.shiftTue && recruitWorkTime.shiftWed && recruitWorkTime.shiftThur && recruitWorkTime.shiftFri) {
        this.workDate_1 = "工作日"
      } else {
        let work_arr = []
        if(recruitWorkTime.shiftMon){
          work_arr.push('周一')
        }
        if (recruitWorkTime.shiftTue) {
          work_arr.push('周二')
        }
        if (recruitWorkTime.shiftWed) {
          work_arr.push('周三')
        }
        if (recruitWorkTime.shiftThur) {
          work_arr.push('周四')
        }
        if (recruitWorkTime.shiftFri) {
          work_arr.push('周五')
        }
        //字符串拼接
        this.workDate_1 = work_arr.join('、')
      }
      //工作类型(1：做一休一，2：做二休一，3：做二休二，4：做五休二，5：做六休一)
      switch (recruitWorkTime.workType) {
        case 1:
          this.workTypeText = "做一休一"
          break;
        case 2:
          this.workTypeText = "做二休一"
          break;
        case 3:
          this.workTypeText = "做二休二"
          break;
        case 4:
          this.workTypeText = "做五休二"
          break;
        case 5:
          this.workTypeText = "做六休一"
          break;
        default:
          break;
      }

      if (recruitWorkTime.shiftSat && recruitWorkTime.shiftSun) {
        this.workDate_2 = "双休日"
      } else {
        if (recruitWorkTime.shiftSat) {
          this.workDate_2 = "周六"
        }
        if (recruitWorkTime.shiftSun) {
          this.workDate_2 = "周日"
        }
      }

      //宿舍距离(1:500米以内，2:1公里以内，3:2公里以内，4:2~5公里，5:5公里以外)
      switch (postRes.dormitoryDistance) {
        case 1:
          this.dormitoryDistance = "500米以内"
          break;
        case 2:
          this.dormitoryDistance = "1公里以内"
          break;
        case 3:
          this.dormitoryDistance = "2公里以内"
          break;
        case 4:
          this.dormitoryDistance = "2~5公里"
          break;
        case 5:
          this.dormitoryDistance = "5公里以外"
          break;
        default:
          break;
      }

      //刷新页面
      this.setData({
        postInfo: this.postInfo,//原始数据
        dormitoryDistance:this.dormitoryDistance,//宿舍距离
        updateTimeStr: timeUtil.parseTime(postRes.updateTime,'{y}-{m}-{d}'),
        jobPayPrice:jobUtil.getPrice(postRes),
        jobPayUnit:jobUtil.commissionUnit(postRes.jobPayUnit),
        operationType: postRes.collected?1:0,//是否收藏岗位
        type2_work_time: this.type2_work_time,//兼职周期
        jobTimeB: this.jobTimeB,//班次数组
        workDate_1: this.workDate_1,//工作日
        workDate_2: this.workDate_2,//双休日
        workTypeText: this.workTypeText,//工作类型(1：做一休一，2：做二休一，3：做二休二，4：做五休二，5：做六休一)
        educationRequire: jobUtil.educationRequire(postRes.educationRequire),//学历要求
        experienceRequire:jobUtil.experienceRequire(postRes.experienceRequire),//经验要求
        genderRequire:jobUtil.genderRequire(postRes.genderRequire),//性别要求
        ageRequire:jobUtil.getAge(postRes),//年龄要求
      })
      if (postRes.collected) {
        this.operationType = 1
        console.log(this.operationType)
      } else {
        this.operationType = 0
        console.log(this.operationType)
      }
      

      // this.setData({
      //   painterView: true
      // })

      //获取推荐列表
      // if (this.latitude) {
        this.getRecommend()
      // }

    });
  },

  // 幻灯片事件
  changeBanner(e) {
    this.setData({
      bannerCurrent: e.detail.current
    })
  },

  //获取微领队的分享令牌
  othersVleaderShareToken() {
    let that = this;
    let commitData = {
      vleaderId: this.shareId
    }
    app.$http.othersVvleaderShareToken(commitData).then(res=>{
      that.id = res.recruitId
      that.otherShareToken = res.shareToken
      setOtherShareToken(res.shareToken)
      if (that.otherShareToken && that.shareFlag) {
        //校验招聘需求分享有效性
        that.getLoadPost()
        //获取岗位详情数据
        that.getDetail()
        //获取分享图片
				that.getShareImage()
      }
    })
  },

  // 获取后端返回分享生成图片
  getShareImage(){
    let that = this;
    let commitData = {
      id: this.id,
    }
    app.$http.getShareImage(commitData).then(res=>{
      that.palette = JSON.parse(res)
      this.setData({
        palette: that.palette
      })
      console.log("获取后端返回分享生成图片")
      console.log(res)
    })
  },
  //校验招聘需求分享有效性
  getLoadPost(){
    let that = this;
    let commitData = {
      recruitId: this.id,
      shareToken: this.shareToken
    }
    app.$http.othersVvleaderShareToken(commitData).then(res=>{
      // if(res.code === 20100){
        that.invalid_vleader = true
        that.failLoadPost.isOwn = res.isOwn
        that.failLoadPost.name = res.name
        // console.log('otherShareToken::',that.otherShareToken)
      // }
    })
  },

  //更多招聘推荐
  getRecommend() {
    let that = this;
    let commitData = {
      jobType: this.jobType,
      lat: this.latitude,
      lng: this.longitude,
      offset: 0,
      limit: 2,
      recruitId: this.id
    }

    app.$http.getJobDetailRecommend(commitData).then(res=>{
      //添加两个属性
      res.forEach(element => {
        element.jobPayPrice = jobUtil.getPrice(element)
        element.jobPayUnit = jobUtil.commissionUnit(element.jobPayUnit)
      });
      that.setData({
        recommend_list: res
      })

      
    })

  },

  // 收藏岗位与取消
  collectionOperation(){
    let that = this;
    // 判断用户是否登录
    if(!getApp().globalData.token){
      this.collectionOperationDis = true
      //前往登录页面
      getApp().$routes.goTo(getApp().$routes.loginPage);
      return false
    }

    let collectionData = {
      tenantId: this.tenantId,
      recruitId: this.id,
      operationType: this.operationType,
    }
    that.setData({
      operationType:this.operationType==1?0:1
    })
    this.operationType=this.operationType==1?0:1
    app.$http.jobDetailCollect(collectionData).then(res=>{
      //提示
      wx.showToast({
        title: collectionData.operationType?'取消收藏':'已收藏',
      })
    })

    
  },

  //我的门店页面
  goMyStore(e){
    const storeID = this.postInfo.storeId;
    let passMap = {
      "id": storeID,
    }
    getApp().$routes.goTo(getApp().$routes.my_store,passMap);
  },

  /*************************其他方法****************** */
  // 打开地图
  openMap(){
    wx.openLocation({
      name: this.postInfo.storeName,
      address: this.postInfo.address,
      latitude: this.postInfo.lat,
      longitude: this.postInfo.lng,
      scale: 18
    })
  },
  // 生成分享海报图片
  onImgOK(e) {
    this.shareQrImg = e.detail.path
    console.log(e)
  },
  //举报
  callPhone(){
    wx.makePhoneCall({
      phoneNumber: '400-872-8880',
    })
  },
  //图片预览
  handlePrevewImage(e){
    //图片数组
    const urls = this.postInfo.workplacePictures
    // 2 接收传递过来的图片url
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current:current,
      urls: urls,
    })
  },

  //申请面试
  showTimePop(){
    //进入我的简历
    getApp().$routes.goTo(getApp().$routes.resumeDetail);
    
    // const popView = this.selectComponent('#popView');
    // popView.open()
  },

  /***********************系统方法******************** */
  //右上角的分享
  onShareAppMessage(res){
    return {
			title: '大圣抢班',
			imageUrl: this.shareQrImg,
			path: `/pages/main/index/postDetail/postDetail??shareToken=${this.selfShareToken}&id=${this.id}&type=${this.jobType}&creatorType=10&shareFlag=true`
		} 
  }
})